package com.zyx.flinkdemo.sql.window.sql.time;

import com.zyx.flinkdemo.pojo.WaterSensor;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @author zyx
 * @since 2021/5/30 08:01
 * desc: 使用SQL 查询基于 处理时间 的 滑动窗口 案例
 */
public class HopProcessTimeDemo {
    public static void main(String[] args) throws Exception {
        // 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 2.读取端口数据创建流并转换每一行数据为JavaBean对象
        SingleOutputStreamOperator<WaterSensor> waterSensorDs = env
                .socketTextStream("linux201", 7777)
                .map(line -> {
                    String[] split = line.split(",");
                    return new WaterSensor(split[0],
                            Long.parseLong(split[1]),
                            Integer.parseInt(split[2]));
                });

        // 3.将流转换为表并指定处理时间
        Table table = tableEnv.fromDataStream(waterSensorDs,
                $("id"),
                $("ts"),
                $("vc"),
                $("pt").proctime());
        tableEnv.createTemporaryView("water_sensor", table);

        // 4.SQL 实现滚动时间窗口
        Table result = tableEnv.sqlQuery("select " +
                "id," +
                "count(id)," +
                "hop_start(pt, INTERVAL '2' second, INTERVAL '5' second) as windowStart," +
                "hop_end(pt, INTERVAL '2' second, INTERVAL '5' second) as windowEnd " +
                "from water_sensor " +
                // 滑动窗口第一个interval参数表示滑动时间, 第二个interval才表示窗口大小!!!!!
                "group by id, hop(pt, INTERVAL '2' second, INTERVAL '5' second)");

        // 5.将结果表转换为流进行输出
        // tableEnv.toAppendStream(result, Row.class).print()

        // 5.直接输出表
        result.execute().print();

        //6.执行任务
        env.execute();
    }
}
